package cn.gzmli.dtt.common.controll;

import cn.gzmli.dtt.common.config.cache.Config;
import cn.gzmli.dtt.common.entity.Result;
import cn.gzmli.dtt.common.entity.User;
import cn.gzmli.dtt.common.entity.vo.UserVO;
import cn.gzmli.dtt.common.service.UserService;
import cn.gzmli.dtt.common.service.log.LogExecutor;
import cn.gzmli.dtt.common.service.log.LoginLogService;
import cn.gzmli.dtt.common.service.log.LoginLogThread;
import cn.gzmli.dtt.common.service.log.UserOnlineLogService;
import cn.gzmli.dtt.common.utils.BaseUtil;
import cn.gzmli.dtt.common.utils.Constant;
import com.xiaoleilu.hutool.util.StrUtil;
import jdk.nashorn.internal.ir.annotations.Ignore;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Descript 系统登录与注销接口
 * @Author xsx
 * @Date 2017/12/25
 */
@RestController
@RequestMapping({"/system","/common/system"})
@Ignore
public class SystemController {
    private static final Logger logger = Logger.getLogger(SystemController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private LoginLogService loginLogService;
    @Autowired
    private UserOnlineLogService userOnlineLogService;


    @Value("${server.servlet.session.loginedTimeout}")
    private int sessionTimeout;



    @RequestMapping("/login")
    @ResponseBody
    public Result login(
            HttpSession session,
            HttpServletRequest request,
            HttpServletResponse response,
            String userName,
            String password,
            String cid,
            String type
    ) throws Exception{

        Result result;
        Map<String, String> condition = new HashMap<>();
        condition.put("userName=", StrUtil.wrap(userName,"'", "'"));
        condition.put("password=", StrUtil.wrap(password,"'", "'"));

        result = new Result(Constant.SUCCESS, "登录成功");
        User user = this.userService.getByCondition(condition);

        if (user==null){
            result = new Result(Constant.FAIL, "用户名或密码错误");
            return result;
        }else {

            if (Constant.DISABLE==user.getStatus().intValue()){
                result = new Result(Constant.FAIL, "账号已禁用删除");
                return result;
            }

            //登录成功更新当前用户的clientID
            if(StrUtil.isNotBlank(type) && type.equals("app")){
                if(StrUtil.isBlank(cid)){
                    return new Result(Constant.FAIL, "当前客户端正在采集用户编号，请2秒之后再重新登录！");
                }
                this.userService.updateUserClientID(userName,cid);
            }

            user.loadRoleAndMenu();
            //缓存当前用户机构角色等相关信息
            String userOrgIDs = userService.getUserOrgIDs(user.getId());
            user.setUserOrgIDS(userOrgIDs);
            List<UserVO> userOrg = userService.getUserOrg(user.getId());
            user.setUserOrg(userOrg);

            String userOrgRoleIDs = userService.getUserOrgRoleIDs(user.getId());
            user.setUserOrgRoleIDS(userOrgRoleIDs);
            List<UserVO> userOrgRole = userService.getUserOrgRole(user.getId());
            user.setUserOrgRole(userOrgRole);

            String userRoleIDs = userService.getUserRoleIDs(user.getId());
            user.setUserRoleIDS(userRoleIDs);
            String userRoleNames = userService.getUserRoleNames(user.getId());
            user.setUserRoleNames(userRoleNames);
            String roleMenuIDs = userService.getUserRoleMenuIDs(userRoleIDs);
            user.setUserRoleMenuIDS(roleMenuIDs);
            String roleMenuNames = userService.getUserRoleMenuNames(roleMenuIDs);
            user.setUserRoleMenuNames(roleMenuNames);


            // 添加用户信息缓存
            String token = UUID.randomUUID().toString().replace("-", "");
            Map<String, Object> tokenMap = new HashMap<>();
            tokenMap.put("token",token);
            Config.putLoginedUser(user,request, "LOGIN",token);

            String sessionId = request.getSession().getId();
            BASE64Encoder encoder = new BASE64Encoder();
            byte[] textByte = sessionId.getBytes("UTF-8");
            String encodedSessionId = encoder.encode(textByte);
            Map<String,Object> data=new HashMap<String,Object>();
            data.put("sessionId",sessionId);
            data.put("userId",user.getId());
            result = new Result(Constant.SUCCESS, "登录成功",data);
            request.getSession().setMaxInactiveInterval(sessionTimeout);
            // 加入系统登录日志
            try{
                LogExecutor.execute(
                        new LoginLogThread(
                                request.getSession(),
                                this.loginLogService,
                                this.userOnlineLogService
                        )
                );
            }catch (Exception e){
                logger.error("加入系统登录日志异常", e);
            }
        }


        return result;
    }

    /**
     * 获取系统时间
     * @author wonderful 20180811
     * @param request
     * @param dateFormat  如：'yyyy-MM-dd HH:mm:ss'
     * @param type  时间类型：YEAR 、MONTH 、DATE
     * @param isAdd  是否做加或减法运算 0减1加 空不做运算
     * @param value  加减的值
     * @return
     * @throws Exception
     */
    @RequestMapping("/getSystemTime")
    @ResponseBody
    public Result getSystemTime(HttpServletRequest request,
                                String dateFormat,
                                String type,
                                Integer isAdd,
                                Integer value
                                ) throws Exception{
        SimpleDateFormat sf=new SimpleDateFormat(dateFormat);
        if(BaseUtil.isNotEmpty(type)){
            Calendar specialDate = Calendar.getInstance();
            specialDate.setTime(new Date()); //注意在此处将 specialDate 的值改为特定日期

            if(type.equals("YEAR")){
                if(BaseUtil.isNotEmpty(isAdd)&&isAdd==1&&BaseUtil.isNotEmpty(value)){
                    specialDate.add(Calendar.YEAR,value); //特定时间加运算
                }else if(BaseUtil.isNotEmpty(isAdd)&&isAdd==0&&BaseUtil.isNotEmpty(value)){
                    specialDate.add(Calendar.YEAR,-value); //特定时
                    // 间减运算
                }
            }else if(type.equals("MONTH")){
                if(BaseUtil.isNotEmpty(isAdd)&&isAdd==1&&BaseUtil.isNotEmpty(value)){
                    specialDate.add(Calendar.MONTH,value); //特定时间加运算
                }else if(BaseUtil.isNotEmpty(isAdd)&&isAdd==0&&BaseUtil.isNotEmpty(value)){
                    specialDate.add(Calendar.MONTH,-value); //特定时间减运算
                }
            }else if(type.equals("DATE")){
                if(BaseUtil.isNotEmpty(isAdd)&&isAdd==1&&BaseUtil.isNotEmpty(value)){
                    specialDate.add(Calendar.DATE,value); //特定时间加运算
                }else if(BaseUtil.isNotEmpty(isAdd)&&isAdd==0&&BaseUtil.isNotEmpty(value)){
                    specialDate.add(Calendar.DATE,-value); //特定时间减运算
                }
            }
//           System.out.println(sf.format(specialDate.getTime()));
            return new Result(Constant.SUCCESS, "获取系统时间成功",sf.format(specialDate.getTime()));
        }
        return new Result(Constant.SUCCESS, "获取系统时间成功",sf.format(new Date()));
    }

    @RequestMapping("/logout")
    @ResponseBody
    public Result logout(HttpServletRequest request) throws Exception{
        //uni-app退出登录清除token -------------start
        String platType=request.getParameter("platType")==null?null:request.getParameter("platType");
        if(platType!=null&&platType.equals("APP")){
            String token = request.getParameter("token")==null?null:request.getParameter("token");
            Config.removeUserByToken(token);
        }
        //uni-app退出登录清除token ------------- end

        String sessionId = request.getSession().getId();
        User user = Config.getUser(request);
        if(user!=null)
        {
        this.loginLogService.saveLogout(sessionId, user);
        this.userOnlineLogService.saveOrUpdate(sessionId, user);
        Config.removeLoginedUser(request);
        return new Result(Constant.SUCCESS, "注销成功");
        }
        else{
            return new Result(Constant.SUCCESS, "注销成功");
        }
    }

    @RequestMapping("/getUserInfo")
    @ResponseBody
    public Result getUserInfo(HttpServletRequest request) throws Exception {
        User user = Config.getUser(request);
        return new Result(Constant.SUCCESS,"获取用户信息成功",user);

    }
}
